<?php
namespace addons\sdcmarry\library;

use fast\Http;
use think\Config;

class MPLib
{
    const GET_CODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
    const GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    const GET_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo";

    /**
     * 配置信息
     * @var array
     */
    private $config = [];

    public function __construct($options = [])
    {
        if ($config = Config::get('sdcmarry.mp')) {
            $this->config = array_merge($this->config, $config);
        }
        $this->config = array_merge($this->config, is_array($options) ? $options : []);
    }
    /**
     * 获取用户信息
     * @param array $params
     * @return array
     */
    public function getLoginInfo($params = [])
    {
        $params = $params ? $params : request()->get();
        if (!isset($params['code'])) {
            return [];
        }
        $data = isset($params['code']) ? $this->codeToSession($params['code']) : $params;
        $openid = isset($data['openid']) ? $data['openid'] : '';
        $session_key = isset($data['session_key']) ? $data['session_key'] : '';
        if (!$openid || !$session_key){
            return [];
        }
        $token_data = $this->getAccessToken();
        $access_token = isset($token_data['access_token']) ? $token_data['access_token'] : '';
        if(!$access_token){
            return [];
        }
        $data['access_token'] = $access_token;
        $data['expires_in'] = $token_data['expires_in'];
        $data['refresh_token'] = isset($data['refresh_token'])? $data['refresh_token'] : '';
        return $data;

    }

    public function codeToSession($code)
    {
        if (!$code) {
            return [];
        }
        $queryarr = array(
            "appid"      => $this->config['app_id'],
            "secret"     => $this->config['app_secret'],
            "js_code"       => $code,
            "grant_type" => "authorization_code",
        );
        $response = Http::get(self::GET_CODE_TO_SESSION_URL, $queryarr);
        $ret = (array)json_decode($response, true);
        return $ret ? $ret : [];
    }

    /**
     * 获取access_token
     * @param string code
     * @return array
     */
    public function getAccessToken()
    {
        $queryarr = array(
            "appid"      => $this->config['app_id'],
            "secret"     => $this->config['app_secret'],
            "grant_type" => "client_credential",
        );
        $response = Http::get(self::GET_ACCESS_TOKEN_URL, $queryarr);
        $ret = (array)json_decode($response, true);
        return $ret ? $ret : [];
    }
}